<?php
define('CONTENT_DRAFT', 1);        // Can edit
define('CONTENT_SUBMITTED', 2);     // Can edit
define('CONTENT_REVISE_NEEDED', 3); // Can edit
define('CONTENT_ACCEPTED', 4);
define('CONTENT_REJECTED', 5);
class Content {
    
    function __construct() {
        
    }

    static public function post($data){
        global $dbdefault;
        //Validation
        $form_error=array();
        if (empty($data['content_title'])) $form_error['content_title']='Chưa có tiêu đề!';
        if (empty($data['content_text'])) $form_error['content_text']='Chưa có nội dung!';
        $len = mb_strlen($data['content_text'],'UTF-8');
        if ($len>480) $form_error['content_text']='Nội dung không được dài quá 480 ký tự!';
        if (!$data['category_id']) $form_error['category_id']='Cần chọn một chuyên mục!';
        if (count($form_error)){
            return array('success'=>FALSE,'form_error'=>$form_error);
        }
        
        $query=sprintf("INSERT INTO contents (category_id,content_title,content_u_title,
            content_text,content_u_text,status,user_id,user_name,post_time,content_source)
            VALUE(%d,%s,%s,%s,%s,%d,%d,%s,%d,%s)",
            qs($data['category_id']),qs($data['content_title']),qs($data['content_u_title']),
            qs($data['content_text']),qs($data['content_u_text']),qs($data['status']),qs($data['user_id']),qs($data['user_name']),
            time(),qs($data['content_source']));
         $res = mysql_query($query,$dbdefault) or die(__CLASS__.':'.__LINE__.':'.mysql_error());
         $content_id = mysql_insert_id();
         return array('success'=>TRUE,'content_id'=>$content_id);
    }

    static public function post_media(){
        global $dbdefault;
        
        if(isset($_FILES['meta_file'])){
            if ($csv = read_CSV($_FILES['meta_file']['tmp_name'], true)) {
                $message='';
                foreach($csv as $data){
                    $message .= "<br/>Processing file $data[filename]...";
                    $r=Content::move_and_insert_media($data);
                    if($r['success']){
                        $message .='<span class="success">Thành công</span>';
                        $message .='<span class="info">'.$r['notice'].'</span>';                       
                    }else{
                        $message .= '<span class="error">'.$r['error'].'</span>';                        
                    }
                }
            }else{
                $message='<span class="error">Không có file upload</span>';
            } 
        }else{
            $message='<span class="error">Không có file upload</span>';
        }
        return $message;
    }
    
    // This is a normal edit
    static public function update($data,$mode='user'){
        global $dbdefault;
        $updates = array();
        $updates[]=sprintf('category_id=%d',  quote_smart($data['category_id']));
        $updates[]=sprintf('content_title=%s',  quote_smart($data['content_title']));
        $updates[]=sprintf('content_u_title=%s',  quote_smart($data['content_u_title']));
        $updates[]=sprintf('content_text=%s',  quote_smart($data['content_text']));
        $updates[]=sprintf('content_u_text=%s',  quote_smart($data['content_u_text']));
        $updates[]=sprintf('content_source=%s',  quote_smart($data['content_source']));
        if (isset($data['status']))  $updates[]=sprintf('status=%d',  quote_smart($data['status']));
        if (isset($data['content_hist']))  $updates[]=sprintf('content_hist=%s',  quote_smart($data['content_hist']));
        
        //print_r($updates);
        $where=  sprintf('content_id=%d', $data['content_id']);
        $r = mysql_update('contents',$updates,$where);
        if ($r['success']){
            return array('success'=>TRUE);
        }else{
            return array('success'=>FALSE,'error'=>$r['error']);
        }
    }

    static public function search($data){
        global $dbdefault;
        $item_per_page = ITEMS_PER_PAGE;
        $start_date=$data['start_date'];
        $end_date=$data['end_date'];
        if (!empty($data['content_id'])){
            $query = sprintf('SELECT * FROM contents WHERE content_id=%d',  qs($data['content_id']));
            $result = mysql_query($query, $dbdefault);
            if (mysql_num_rows($result)){
                $contents[] = mysql_fetch_assoc($result); 
                return array('success'=>TRUE,'contents'=>$contents,'total_pages'=>1,'page'=>1);    
            }else{
                return array('success'=>FALSE,'error'=>'Không tìm thấy bài viết #'.$data['content_id']);    
            }
        }
        ////
        $ws = array();
        if ($data['category_id']){
            $ws[] = sprintf('category_id=%d',$data['category_id']);
        }
        if ($data['user_id']){
            $ws[] = sprintf('user_id=%d',$data['user_id']);
        }        
        if (!empty($data['content_title'])){
            $keywords = stripcslashes($data['content_title']);
            $ws[] = "`content_title` LIKE '%$keywords%'";
        }        
        if (!empty($data['artist'])){
            $keywords = stripcslashes($data['artist']);
            $ws[] = "`artist` LIKE '%$keywords%'";
        }        
        if (!empty($data['author'])){
            $keywords = stripcslashes($data['author']);
            $ws[] = "`author` LIKE '%$keywords%'";
        }        
        if (!empty($data['platform'])){
            $keywords = stripcslashes($data['platform']);
            $ws[] = "`platform` LIKE '%$keywords%'";
        }        

       if (!empty($start_date)){
            list($dd,$mm,$yyyy) =  explode('/', $start_date);
            $sdate=mktime(0,0,0,$mm,$dd,$yyyy);
            $ws[] = "post_time>$sdate";
        }
        
        if (!empty($end_date)){
            list($dd,$mm,$yyyy) =  explode('/', $end_date);
            $edate=mktime(23,59,59,$mm,$dd,$yyyy);
            $ws[] = "post_time<$edate";
        }
        
        
        if (!count($ws)){
            return array('success'=>FALSE,'error'=>'Bạn phải chọn ít nhất một tiêu chí');   
        }
        //$ws[]='status='.CONTENT_ACCEPTED;
        $where = implode(' AND ', $ws);
        //Get total pages
        $query = "SELECT count(*) as total FROM contents WHERE $where";
        echo $query;
        $result = mysql_query($query,$dbdefault) or die(__CLASS__."->".__LINE__.": ".  mysql_error());
        $total = mysql_result($result, 0, 'total');
        $total_pages = ceil($total/$item_per_page);
        $page = $data['page'];
        if ($page>$total_pages)$page=$total_pages;
        if ($page<1)$page=1;
        
        $limit = ($page-1)*$item_per_page;
        $offset = $item_per_page;
        $query = "SELECT * FROM contents WHERE $where
                  ORDER BY `post_time` DESC LIMIT $limit, $offset";

        $result = mysql_query($query,$dbdefault) or die(__CLASS__."->".__LINE__.": ".  mysql_error());

        if (mysql_num_rows($result)){
            $contents = array();
            while($arr=  mysql_fetch_assoc($result)){
                $contents[]=$arr;
            }
            return array('success'=>TRUE,'contents'=>$contents,'total_pages'=>$total_pages,'page'=>$page);    
        }else{
            return array('success'=>FALSE,'error'=>'Không tìm thấy bài viết');    
        }
        
        
        return array('success'=>FALSE,'error'=>'Unknown error');        
    }

    static public function delete($content_id){
        global $dbdefault;
 
    }

    
    static public function move_and_insert_media($data){
        global $dbdefault;
        require_once(LIB.'/class_Image.php');
        //debug_data($data);
        //Check if file exists
        $uploaded_file=UPLOADS.'/'.$data['filename'];
        if(!file_exists($uploaded_file)){
            return array('success'=>FALSE,'error'=>'File không tồn tại');
        }        
        //Check if file already uploaded
        $query=sprintf("SELECT count(*) AS total FROM contents WHERE media_url=%s",qs($data['filename']));
        $result = mysql_query($query, $dbdefault) or die(mysql_error().':'.__LINE__.$query);
        $total = mysql_result($result, 0, 'total');
        if ($total){
            return array('success'=>FALSE,'error'=>'File đã tồn tại trong hệ thống');
        }        
        //Move to storage and insert into database
        $des_path = Content::get_media_path($data['filename'], $data['media_type']);
        //echo "<br>$uploaded_file, $des_path"; 
        if (!copy($uploaded_file, $des_path )) die ("Cannot copy file!");
        ////unlink($uploaded_file);
        
        //check if there is thumbnail
        $notice='';
        $data['media_thumb']='';
        if (!empty($data['thumbnail'])){
            $im = new Image(UPLOADS.'/'.$data['thumbnail']);
            $time = time();
            $data['media_thumb']=basename($data['filename'])."_thumb.jpg";
            $thumb_src=DATA.'/thumbs/'.$data['media_thumb'];
            if (!$im->gd_im) {
                $data['media_thumb']='';
                $notice=' (Không tạo được thumbnail)';
            }
            $im->resize($thumb_src,240,180);
        }else{
            $notice='Không tạo được thumbnail';
        }
        
        //Additonal info
        $data['content_u_title'] = VN_unaccent($data['content_title']);
        $data['content_u_text'] = VN_unaccent($data['content_text']);
        $data['user_id'] = SESSION_value('user_id',0);
        $data['user_name'] = SESSION_value('user_name','');
        $data['status']=CONTENT_ACCEPTED;        
        $query=sprintf("INSERT INTO contents (category_id,content_title,content_u_title,
            content_text,content_u_text,status,user_id,user_name,post_time,
            media_url,media_type,media_thumb,artist,author,platform)
            VALUE(%d,%s,%s,%s,%s,%d,%d,%s,%d,%s,%s,%s,%s,%s,%s)",
            qs($data['category_id']),qs($data['content_title']),qs($data['content_u_title']),qs($data['content_text']),
            qs($data['content_u_text']),qs($data['status']),qs($data['user_id']),qs($data['user_name']),time(),
            qs($data['filename']),qs($data['media_type']),qs($data['media_thumb']),
            qs($data['artist']),qs($data['author']),qs($data['platform']));
         $res = mysql_query($query,$dbdefault) or die(__CLASS__.':'.__LINE__.':'.mysql_error());
         $content_id = mysql_insert_id();
         return array('success'=>TRUE,'content_id'=>$content_id,'notice'=>$notice);
    }
            
    static public function get_media_path($filename,$media_type){
        switch ($media_type){
            case GAME:
                return DATA.'/games/'.$filename;break;
            case MUSIC:
                return DATA.'/musics/'.$filename;break;
            case IMAGE:
                return DATA.'/images/'.$filename;break;
            case CLIP:
                return DATA.'/clips/'.$filename;break;
            default:
                return '';
        }
    } 
    
    static public function get_media_url($filename,$media_type){
        switch ($media_type){
            case GAME:
                return DATA_URL.'/games/'.$filename;break;
            case MUSIC:
                return DATA_URL.'/musics/'.$filename;break;
            case IMAGE:
                return DATA_URL.'/images/'.$filename;break;
            case CLIP:
                return DATA_URL.'/clips/'.$filename;break;
            default:
                return '';
        }
    } 
    static public function get_thumb_url($filename){
        return DATA_URL.'/thumbs/'.$filename;
    } 

}